package com.example.telephoneBook;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.R.string;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.sql.HttpThread;
import com.example.sql.PNBean;
import com.example.sql.PNOperator;
import com.example.telephoneBook.otherPackage.CharacterParser;
import com.example.telephoneBook.otherPackage.PinyinComparator;
import com.example.telephoneBook.otherPackage.SideBar;
import com.example.telephoneBook.otherPackage.SortAdapter;
import com.example.telephoneBook.otherPackage.SortModel;

public class MainListActivity extends Activity {

	private SideBar mSideBar;
	private SortAdapter adapter;
	private TextView mDialog;
	private ListView sortListView;
	private CharacterParser characterParser;
	private PinyinComparator pinyinComparator;
	private List<SortModel> sourceDateList;
	private int wayindex = 0;
	private int peopleindex = 0;
	private ArrayList<PNBean> list = new ArrayList<PNBean>();

	// private AutoCompleteTextView mSearchText;
	// private Button mSearchButton;
	private String[] data;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main_list);
		setOverflowShowingAlways();

		characterParser = CharacterParser.getInstance();
		pinyinComparator = new PinyinComparator();

		mSideBar = (SideBar) findViewById(R.id.sidebar);
		mDialog = (TextView) findViewById(R.id.tv_dialog);
		mSideBar.setTextView(mDialog);

		mSideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {

			@Override
			public void onTouchingLetterChanged(String s) {
				int position = adapter.getPositionForSection(s.charAt(0));
				if (position != -1) {
					sortListView.setSelection(position);
				}
			}
		});

		sortListView = (ListView) findViewById(R.id.lv_c);
		sortListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				peopleindex = arg2;
				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainListActivity.this);
				builder.setIcon(R.drawable.ic_launcher);
				builder.setTitle(sourceDateList.get(arg2).getName());
				final String[] funtion = {
						"长号:" + list.get(arg2).getPhoneNumber(),
						"短号:" + list.get(arg2).getShortNumber() };

				// 设置一个单项选择下拉框
				/**
				 * 第一个参数指定我们要显示的一组下拉单选框的数据集合 第二个参数代表索引，指定默认哪一个单选框被勾选上，1表示默认'长号'
				 * 会被勾选上 第三个参数给每一个单选项绑定一个监听器
				 */
				builder.setSingleChoiceItems(funtion, 0,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								wayindex = which;
							}

						});
				builder.setPositiveButton("拨号",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								String number = null;
								if (wayindex == 0) {
									number = list.get(peopleindex)
											.getPhoneNumber();
								} else {
									number = list.get(peopleindex)
											.getShortNumber();
								}
								Intent intent = new Intent(Intent.ACTION_CALL,
										Uri.parse("tel:" + number));
								MainListActivity.this.startActivity(intent);
								Toast.makeText(getApplicationContext(),
										"拨号" + number, Toast.LENGTH_SHORT)
										.show();
							}
						});
				builder.setNeutralButton("短信",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								String number = null;
								if (wayindex == 0) {
									number = list.get(peopleindex)
											.getPhoneNumber();
								} else {
									number = list.get(peopleindex)
											.getShortNumber();
								}

								sendSMS("", number);
								Toast.makeText(getApplicationContext(),
										"短信" + number, Toast.LENGTH_SHORT)
										.show();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Toast.makeText(getApplicationContext(), "取消",
										Toast.LENGTH_SHORT).show();
							}
						});
				builder.show();

			}
		});

		// PNOperator pno = new PNOperator(this);
		// 测试用插入数据，每次运行都会插入
		// pno.insert(new PNBean(1,"test1","123"));
		// pno.insert(new PNBean(2,"test2","2524356"));
		// pno.insert(new PNBean(3,"aTExt","46587346"));
		String url = "http://10.82.11.166/Testp/getPhoneNunber.php";
		new HttpThread(url, this).start();

		list = new ArrayList<PNBean>();
		list = new PNOperator(this).quary();
		int i = 0;
		while (list.size() == 0) {
			
			try {
				Thread.sleep(1000);
				System.out.println("第" + i + "次睡眠");
				i++;
				list = new PNOperator(this).quary();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}// 睡眠1000毫秒

		}
		//
		sourceDateList = filledData(list);

		Collections.sort(sourceDateList, pinyinComparator);
		adapter = new SortAdapter(this, sourceDateList);
		sortListView.setAdapter(adapter);

		// mSearchText = (AutoCompleteTextView) findViewById(R.id.tv_search);
		ArrayAdapter arrAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, data);
		// mSearchText.setAdapter(arrAdapter);

		// mSearchButton = (Button) findViewById(R.id.btn_search);
		// mSearchButton.setOnClickListener(new View.OnClickListener() {
		// @Override
		// public void onClick(View v) {
		// // 跳转
		// }
		// });
	}

	private List<SortModel> filledData(ArrayList<PNBean> list) {
		List<SortModel> mSortList = new ArrayList<SortModel>();
		data = new String[list.size()];
		for (int i = 0; i < list.size(); i++) {
			if(list.get(i).getName() == null){
				break;
			}
			PNBean bean = list.get(i);
			SortModel sortModel = new SortModel();
			data[i] = bean.getName();
			sortModel.setName(data[i]);
			String pinyin = characterParser.getSelling(data[i]);
			String sortString = pinyin.substring(0, 1).toUpperCase();

			if (sortString.matches("[A-Z]")) {
				sortModel.setSortLetters(sortString.toUpperCase());
			} else {
				sortModel.setSortLetters("#");
			}
			sortModel.setId(bean.getId());
			mSortList.add(sortModel);
		}
		return mSortList;
	}

	private void setOverflowShowingAlways() {
		try {
			ViewConfiguration config = ViewConfiguration.get(this);
			Field menuKeyField = ViewConfiguration.class
					.getDeclaredField("sHasPermanentMenuKey");
			menuKeyField.setAccessible(true);
			menuKeyField.setBoolean(config, false);
		} catch (Exception e) {
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		if (featureId == Window.FEATURE_ACTION_BAR && menu != null) {
			if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
				Method m = null;
				try {
					m = menu.getClass().getDeclaredMethod(
							"setOptionIconsVisible", Boolean.TYPE);
					m.setAccessible(true);
					m.invoke(menu, true);
				} catch (Exception e) {
				}
			}
		}
		return super.onMenuOpened(featureId, menu);
	}

	private void sendSMS(String smsBody, String number)

	{

		Uri smsToUri = Uri.parse("smsto:" + number);

		Intent intent = new Intent(Intent.ACTION_SENDTO, smsToUri);

		intent.putExtra("sms_body", smsBody);

		startActivity(intent);

	}

}